package com.action.ui.fragment;


import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.action.childbase.ChildBaseFragment;
import com.base.app_core.View.xrecyclerview.RecyclerAdapter;
import com.base.app_core.View.xrecyclerview.RecyclerViewHolder;
import com.base.app_core.model.Paginated;
import com.base.app_core.model.TodayHistoryStock;
import com.base.app_core.service.pressenter.XYBUPressenter;
import com.base.app_core.service.user.model.User;
import com.base.app_core.service.user.model.UserAccount;
import com.base.app_core.util.AppConstants;
import com.xinglai.yun.R;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.qq.e.ads.banner.ADSize;
import com.qq.e.ads.banner.AbstractBannerADListener;
import com.qq.e.ads.banner.BannerView;
import com.qq.e.comm.util.AdError;

import java.util.Collection;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class HistoryStockPriceFragment extends ChildBaseFragment<XYBUPressenter> {

    @Inject
    User user;
    @Inject
    UserAccount userAccount;

    @BindView(R.id.stock_price)
    TextView stockPrice;

    @BindView(R.id.data_container)
    XRecyclerView dataContainer;

    @BindView(R.id.bannerContainer)
    FrameLayout adView;

    private StockPriceAdapter stockPriceAdapter;
    private int pageNO = 1;

    public static class StockPriceAdapter extends RecyclerAdapter<TodayHistoryStock, StockPriceAdapter.ViewHolder> {


        private FragmentActivity activity;

        public StockPriceAdapter(FragmentActivity activity) {
            super();
            this.activity = activity;
        }

        @Override
        protected void fillData(TodayHistoryStock item, final StockPriceAdapter.ViewHolder holder) {
            holder.changeDate.setVisibility(View.VISIBLE);
            holder.currentPrice.setVisibility(View.VISIBLE);

            holder.changeDate.setText(item.getUpdateAt());
            holder.currentPrice.setText(item.getCurrentPrice());
        }

        @Override
        protected int getItemLayoutId() {
            return R.layout.unit_stock_price_log_com;
        }

        public class ViewHolder extends RecyclerViewHolder {
            @BindView(R.id.change_date)
            TextView changeDate;
            @BindView(R.id.current_price)
            TextView currentPrice;

            public ViewHolder(View itemView) {
                super(itemView);
            }

        }
    }


    @Override
    protected void initView() {
        super.initView();
        setToolBar("股价详情");
        stockPrice.setText(userAccount.getStockPrice());
        stockPriceAdapter = new StockPriceAdapter(getActivity());
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        dataContainer.setLayoutManager(layoutManager);
        dataContainer.setAdapter(stockPriceAdapter);
        dataContainer.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        dataContainer.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                if (dataContainer == null) {
                    return;
                }
                pageNO = 1;
                if (null != mPresenter) {
                    mPresenter.fetchStockPriceLog(pageNO);
                }

                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (dataContainer != null) {
                            dataContainer.refreshComplete();
                        }
                    }
                }, AppConstants.Const.REFRESHTIME);
            }

            @Override
            public void onLoadMore() {
                pageNO++;
                if (null != mPresenter)
                    mPresenter.fetchStockPriceLog(pageNO);
                dataContainer.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != dataContainer)
                            dataContainer.loadMoreComplete();
                    }
                }, AppConstants.Const.REFRESHTIME);
            }
        });
        dataContainer.setEmptyView(getEmptyView(dataContainer, "当前金米价为没有波动记录", "", null));

        requestGDTBanner();
    }

    private void requestGDTBanner() {
        BannerView bv = new BannerView(getActivity(), ADSize.BANNER, "1107815226", "8070337977963314");
        // 注意：如果开发者的banner不是始终展示在屏幕中的话，请关闭自动刷新，否则将导致曝光率过低。
        // 并且应该自行处理：当banner广告区域出现在屏幕后，再手动loadAD。
        bv.setRefresh(30);
        bv.setADListener(new AbstractBannerADListener() {

            @Override
            public void onNoAD(AdError error) {
                Log.i(
                        "AD_DEMO",
                        String.format("Banner onNoAD，eCode = %d, eMsg = %s", error.getErrorCode(),
                                error.getErrorMsg()));
            }

            @Override
            public void onADReceiv() {
                Log.i("AD_DEMO", "ONBannerReceive");
            }
        });
        adView.addView(bv);
        bv.loadAD();
    }

    @Override
    protected boolean isNeedShowLoading() {
        return true;
    }

    @Override
    protected boolean needShowError() {
        return true;
    }

    @Override
    protected void loadData() {
        super.loadData();
        mPresenter.fetchStockPriceLog(pageNO);
    }

    @Override
    protected void setupComponent() {
        super.setupComponent();
        getChildViewComponent().inject(this);
    }

    @Override
    public <T> void notifyData(T object, Class tClass, Paginated paginated) {
        super.notifyData(object, tClass, paginated);
        if (object instanceof Collection) {
            if (tClass == TodayHistoryStock.class) {
                if (stockPriceAdapter == null || dataContainer == null) {
                    return;
                }

                if (pageNO == 1) {
                    stockPriceAdapter.clear();
                }

                List<TodayHistoryStock> o = (List<TodayHistoryStock>) object;
                stockPriceAdapter.addAll(o);
                if (!o.isEmpty()) {
                    stockPrice.setText(o.get(0).getCurrentPrice());
                } else {
                    stockPrice.setText("0");
                }
                stockPriceAdapter.notifyDataSetChanged();

                if (paginated != null) {
                    dataContainer.setLoadingMoreEnabled(paginated.getHasMore());
                }

            }
        }
        setState(AppConstants.STATE_SUCCESS);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_history_stock_price;
    }

}
